package com.pounds.firstgame;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.Collection;
import java.util.Random;

/**
 * Created by Administrator on 2016/10/24.
 */
public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback{
    private boolean runState=false;
    private SurfaceHolder surfaceHolder=null;
    private Bitmap gameBitmap =null;
    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.getHolder().addCallback(this);
        gameBitmap=Bitmap.createBitmap(1080,1920, Bitmap.Config.ARGB_8888);
    }

    public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        runState=true;
        this.surfaceHolder=surfaceHolder;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        runState=false;
    }

    @Override
    public void run() {
        Random random = new Random();

        try {
            while (true){
                Canvas canvas = surfaceHolder.lockCanvas();
                Paint paint = new Paint();
                paint.setColor(Color.WHITE);
                Canvas c = new Canvas(gameBitmap);
                c.drawRect(new Rect(0,0,1080,1920),paint);

                paint.setColor(Color.rgb(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
                c.drawLine(random.nextInt(2056),random.nextInt(2056),random.nextInt(2056),random.nextInt(2056),paint);

                canvas.drawBitmap(gameBitmap,0,0,new Paint());
                surfaceHolder.unlockCanvasAndPost(canvas);
                Thread.sleep(1000);
            }
        }catch (Exception e){
            Log.e("game run ","crash");
        }

    }
}
